import zipfile
import os
import urlparse
from pyurl.url import scheme_registry
from pyurl.protocols.archive import ArchiveConnection, ArchiveURL

class ZipFileObject(object):
    def __init__(self, archive, filename):
        self.archive = archive
        self.filename = filename
        
    def read(self):
        return self.archive.read(self.filename)
    
    def close(self):
        pass
    
class ZipConnection(ArchiveConnection):
    def open_archive(self, file):
        stream = file.open("r")
        zip = zipfile.ZipFile(stream, "r")
        return zip
    
    def exists(self, path):
        return path[1:] in self.archive.namelist()
        
    def open_file(self, path, mode):
        if path[1:] in self.archive.namelist():
            return ZipFileObject(self.archive, path[1:])
        else:
            raise IOError(2, "No such file or directory '"+path[1:]+"'")
    
        
class ZipURL(ArchiveURL):
    _scheme = "zip"
    _connection_type = ZipConnection

scheme_registry.register(ZipURL)